#include "InSdkSpkCtrl.h"

#define SPK_CTRL_CLOSE_TIME 10

Com_u16 g_InSdkSpkCtrl_UseCnt = 0;
Com_s32 g_InSdkSpkCtrl_UseSW = DEF_COM_TRUE;
EnComSpeakerState g_InSdkSpkCtrl_State = SPEAKER_UNKNOW;

void Ext_InSdkSpkCtrl_CntAdd(void)
{
    g_InSdkSpkCtrl_State = SPEAKER_CLOSE;
    if (g_InSdkSpkCtrl_UseCnt < 8)
    {
        g_InSdkSpkCtrl_UseCnt++;
    }
}

void Ext_InSdkSpkCtrl_CntMinus(void)
{
    if (g_InSdkSpkCtrl_UseCnt > 0)
    {
        g_InSdkSpkCtrl_UseCnt--;
    }
}

void Ext_InSdkSpkCtrl_Using(void)
{
    g_InSdkSpkCtrl_State = SPEAKER_USING;
}

void Ext_InSdkSpkCtrl_SetMode(Com_s32 mode)
{
    g_InSdkSpkCtrl_UseSW = mode;
}

Com_pvoid InSdkSpkCtrl_Thread(Com_pvoid arg)
{
    DEF_COM_SET_THREAD_NAME("Speaker_Ctrl",g_ComThread_Num);

    Com_s32 cnt = 0;
    StComSecondTimer timer;

    while (g_ComThread_Running)
    {
        if (g_InSdkSpkCtrl_UseSW == DEF_COM_FALSE)
        {
            if (g_InSdkSpkCtrl_State != SPEAKER_ALWAYS_CLOSE)
            {
                Ext_SdkGpio_Write_Spk(DEF_COM_LEVEL_HIGHT);
                g_InSdkSpkCtrl_State = SPEAKER_ALWAYS_CLOSE;
            }
            usleep(50 * 1000);
            continue;
        }

        if (g_InSdkSpkCtrl_State == SPEAKER_ALWAYS_CLOSE)
        {
            g_InSdkSpkCtrl_State = SPEAKER_UNKNOW;
        }

        /* open spk */
        if ((g_InSdkSpkCtrl_UseCnt > 0) && (g_InSdkSpkCtrl_State == SPEAKER_CLOSE))
        {
            g_InSdkSpkCtrl_State = SPEAKER_USING;
            Ext_SdkGpio_Write_Spk(DEF_COM_LEVEL_LOW);
            Ext_InComTimer_GetSec(DEF_COM_SET_NEW_TIME, &timer);
        }

        /* close spk */
        if ((g_InSdkSpkCtrl_UseCnt == 0) && ((g_InSdkSpkCtrl_State == SPEAKER_USING) ||
                                                (g_InSdkSpkCtrl_State == SPEAKER_UNKNOW)))
        {
            if (cnt >= 60)
            {
                Ext_SdkGpio_Write_Spk(DEF_COM_LEVEL_HIGHT);
                g_InSdkSpkCtrl_State = SPEAKER_CLOSE;
                cnt = 0;
            }
            else
            {
                cnt++;
            }
        }

        if (g_InSdkSpkCtrl_UseCnt > 0)
        {
            cnt = 0;
            if (g_InSdkSpkCtrl_State == SPEAKER_USING)
            {
                g_InSdkSpkCtrl_State = SPEAKER_UNKNOW;
                Ext_InComTimer_GetSec(DEF_COM_SET_NEW_TIME, &timer);
            }

            if (Ext_InComTimer_GetSec(DEF_COM_NOT_SET_TIME, &timer) >= SPK_CTRL_CLOSE_TIME)
            {
                if (g_InSdkSpkCtrl_State != SPEAKER_USING)
                {
                    g_InSdkSpkCtrl_UseCnt = 0;
                    g_InSdkSpkCtrl_State = SPEAKER_CLOSE;
                    Ext_SdkGpio_Write_Spk(DEF_COM_LEVEL_HIGHT);
                }
            }
        }
        usleep(50 * 1000);
    }

    DEF_COM_EXIT_THREAD(g_ComThread_Num);
}

Com_void Ext_InSdkSpkCtrl_Init(Com_void)
{
    pthread_t id;

    pthread_create(&id, NULL, InSdkSpkCtrl_Thread, NULL);
    pthread_detach(id);
}
